package com.example.demo.common.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName="commonFilter",urlPatterns="/*")
public class CommonFilter implements Filter {

	//封装，不需要过滤的list列表
	private static List<Pattern> patterns = new ArrayList<Pattern>();
    
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//配置不需要走过滤器的地址
        patterns.add(Pattern.compile("/api/system/login"));//系统登录
		System.out.println("init filter");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("doFilter");
		HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (isInclude(url)){
            chain.doFilter(httpRequest, httpResponse);
            return;
        } else {
        	//其它校验信息 TODO
        	chain.doFilter(httpRequest, httpResponse);
            return;
        }
	}

	@Override
	public void destroy() {
	}
	 /**
	  * 判断是否需要过滤
	  * @param url
	  * @return
	  */
    private boolean isInclude(String url) {
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }

}
